package cn.bigcontainer.alt.calendar.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bigcontainer.alt.calendar.dto.MCalendar;
import cn.bigcontainer.alt.calendar.dto.MCalendarEvent;
import cn.bigcontainer.alt.calendar.service.MCalendarService;
import cn.bigcontainer.alt.common.entity.WoPage;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MAppDto;
import cn.bigcontainer.alt.meta.dto.MCrud;
import cn.bigcontainer.alt.meta.dto.MObjectDto;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.mapper.MAppMapper;
import cn.bigcontainer.alt.meta.po.MApp;
import cn.bigcontainer.alt.meta.service.MCrudService;
import cn.bigcontainer.alt.sys.dto.UserDto;
import cn.bigcontainer.alt.sys.util.SysUtil;
import cn.bigcontainer.alt.workflow.service.MWorkflowService;
import lombok.extern.slf4j.Slf4j;

@Service
@Transactional
@Slf4j
public class MCalendarServiceImpl implements MCalendarService {

	@Resource
	private MAppMapper appMapper;

	@Override
	public MAppDto loadCalendar(String id, Map<String, Object> req) {
		MApp mApp = appMapper.selectById(id);
		return new MAppDto(mApp);
	}

	@Resource
	private MCrudService crudService;

	@Resource
	private MWorkflowService workflowService;

	@Override
	public List<MCalendarEvent> loadList(String id, String[] subAppIds, String start, String end,
			Map<String, Object> req) {
		UserDto userDto = SysUtil.getCurrentUserWithException(req);
		MApp mApp = appMapper.selectById(id);
		MCalendar mCalendar = new MCalendar(mApp);
		List<MCalendarEvent> events = new ArrayList<MCalendarEvent>();
		// req.put(MViewDto.PARAM_PAGE_SIZE, "20");
		for (MAppDto app : mCalendar.getApps()) {
			if (!Arrays.asList(subAppIds).contains(app.getId())) {
				continue;
			}
			// 增加过滤条件：当前用户 and ((结束时间 is null and 开始时间 >= start and 结束时间 < end) or (开始时间 < end and 结束时间 > start))
			MViewDto view = app.getView(app.getData().getString(MCrud.PARAM_LIST));
			// view.getData().bigPut(MViewDto.PARAM_PAGING, "false"); 此处无效，因为后面调用的是crudService.loadListData，需要在listview中直接配置paging参数
			String filterString = String.format(
					"%s.mcjr0_id = %d "
					+ "and ((%s.mjssj is null and %s.mkssj >= '%s 00:00:00' and %s.mkssj < '%s 00:00:00') "
							+ "or (%s.mkssj < '%s 00:00:00' and %s.mjssj > '%s 00:00:00'))",
					view.getObjectAlias(), userDto.getId(), view.getObjectAlias(), view.getObjectAlias(), start, view.getObjectAlias(), end, view.getObjectAlias(), end,
					view.getObjectAlias(), start);
			req.put(MObjectDto.PREFIX_LIST_FILTER + app.getId(), filterString);
			// 加载列表数据
			MViewDto listView = null;
			if (MAppDto.TYPE_CRUD.equals(app.getType())) {
				listView = crudService.loadListData(app.getId(), req);
			} else if (MAppDto.TYPE_WORKFLOW.equals(app.getType())) {
				listView = workflowService.loadListData(app.getId(), req);
			}
			req.remove(MObjectDto.PREFIX_LIST_FILTER + app.getId());
			WoPage<Map<String, Object>> listData = listView.getListData();
			if (listData == null || listData.getRows().size() == 0) {
				continue;
			}
			for (int i = 0; i < listData.getRows().size(); i++) {
				MCalendarEvent event = new MCalendarEvent();
				event.setId(listView.getListValue(i, 0).toString());
				// 最后一个视图属性，必须是创建人
				// event.setCjrXm((String) listView.getListValue(i, listView.getProperties().size() - 1));
				event.setCjrXm(userDto.getName());
				event.setTitle((String) listView.getListValueBySuffix(i, "mbt"));
				// event.setColor((String)listView.getListValue(i, 2));
				event.setStart((String)listView.getListValueBySuffix(i, "mkssj"));
				event.setEnd((String)listView.getListValueBySuffix(i, "mjssj"));
				Double fzs = WoKit.getDouble(listView.getListValueBySuffix(i, "mfzs"), null);
				event.setMinutes(fzs);
				event.setApp(id);
				event.setSubapp(app.getId());
				event.setStatus((String)listView.getListValueBySuffix(i, "mzt"));
				event = mCalendar.process(event, id, subAppIds, start, end, req);
				if (event == null) {
					continue;
				}
				events.add(event);
			}
		}
		return events;
	}

	@Resource
	private MDao dao;

	@Override
	public MCalendarEvent start(MCalendarEvent e, Map<String, Object> req) {
		MApp app = appMapper.selectById(e.getSubapp());
		String sql = String.format("update %s set mkssj = '%s' %s where mid = '%s'", app.getObjectId(), e.getStart(), WoKit.isEmpty(e.getEnd())? "" : ", mjssj = '" + e.getEnd() + "'", e.getId());
		dao.update(sql);
		return e;
	}

	@Override
	public MCalendarEvent end(MCalendarEvent e, Map<String, Object> req) {
		MApp app = appMapper.selectById(e.getSubapp());
		String sql = String.format("update %s set mjssj = '%s' where mid = '%s'", app.getObjectId(), e.getEnd(), e.getId());
		dao.update(sql);
		return e;
	}

}
